package com.forfunnet.minjian.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

import com.forfunnet.minjian.R;


/**
 * Created by zhangfan on 15/3/5.
 */
public class RatioItemFrame extends RelativeLayout
{
    public RatioItemFrame(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        TypedArray a = getContext().obtainStyledAttributes(attrs,
                R.styleable.RatioItemFrame);
        try
        {
            String ratioStr = a.getString(R.styleable.RatioItemFrame_width_height_ratio);
            if (ratioStr != null)
            {
                String[] parts = ratioStr.split(":");
                if (parts.length == 1)
                {
                    ratio = Float.parseFloat(parts[0]);
                }
                else
                {
                    ratio = Float.parseFloat(parts[0]) / Float.parseFloat(parts[1]);
                }
            }
        }
        catch (Exception e)
        {
            ratio = 0;
        }
        a.recycle();
    }

    float   ratio = 0;
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (ratio > 0)
        {
            int height = Math.round(getMeasuredWidth() / ratio);
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY);
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}
